package jnpf.database.util;

import cn.dev33.satoken.session.SaSession;
import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.ds.GroupDataSource;
import jnpf.database.model.TenantLinkModel;
import jnpf.database.model.TenantVO;
import jnpf.util.JsonUtil;
import jnpf.util.TenantProvider;
import jnpf.util.context.SpringContext;
import jnpf.util.data.DataSourceContextHolder;

import javax.sql.DataSource;
import java.sql.Connection;
import java.util.List;

import static jnpf.database.util.TenantDataSourceUtil.DBLINK_KEY;

public class ConnUtils {

    /**
     * 指定数据库得到Connection
     *
     * @return
     */
    public static Connection getConn() {
        DynamicRoutingDataSource dynamicRoutingDataSource = (DynamicRoutingDataSource) SpringContext.getBean(DataSource.class);
        if (dynamicRoutingDataSource.getGroupDataSources().containsKey(DataSourceContextHolder.getDatasourceId() + "-master")) {
            GroupDataSource groupDataSource = dynamicRoutingDataSource.getGroupDataSources().get(DataSourceContextHolder.getDatasourceId() + "-master");
            if (groupDataSource.getDataSourceMap().size() > 0) {
                String key = "";
                for (String string : groupDataSource.getDataSourceMap().keySet()) {
                    key = string;
                    break;
                }
                DruidDataSource dataSource = (DruidDataSource) groupDataSource.getDataSourceMap().get(key);
                try {
                    return ConnUtil.getConn(dataSource.getUsername(), dataSource.getPassword(), dataSource.getUrl());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 指定数据库得到配置库信息
     *
     * @return
     */
    public static TenantLinkModel getTenantLinkModel() {
        SaSession tenantSession = TenantProvider.getTenantSession(DataSourceContextHolder.getDatasourceId());
        TenantVO jsonToBean = JsonUtil.getJsonToBean(tenantSession.getDataMap().get(DBLINK_KEY), TenantVO.class);
        if (jsonToBean != null) {
            List<TenantLinkModel> linkList = jsonToBean.getLinkList();
            TenantLinkModel tenantLinkModel = linkList.stream().findFirst().orElse(null);
            return tenantLinkModel;
        }
        return null;
    }

}
